package cn.yoyo.service;

import cn.yoyo.dao.LargefileDao;
import cn.yoyo.dao.UserDao;
import cn.yoyo.entity.User;
import cn.yoyo.tools.MySession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    UserDao userDao;
    @Autowired
    LargefileDao largefileDao;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public void add(User user, MultipartFile file) throws Exception{
        if (file!=null&&file.getSize()>0){
            String imgId = largefileDao.saveMultipartFile(file);
            user.setPictureId(imgId);
        }else{
            user.setPictureId("6242e7ef0848ca6aee876bef");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        System.out.println("user="+user.toString());
        userDao.add(user);
    }

    @Override
    public User findById(String userId) {
        return userDao.findById(userId);
    }

    @Override
    public void update(User user,MultipartFile file) throws Exception{
        // 如需更换头像 先取出原先的 一旦更新成功便从桶里删除旧头像
        if (file!=null&&file.getSize()>0){
            String imgId = MySession.getUser().getPictureId();
            String img = largefileDao.saveMultipartFile(file);
            user.setPictureId(img);
            if (imgId!=null){
                largefileDao.deleteById(imgId);
            }
        }
        userDao.update(user);
    }

    @Override
    public void block(String userId,Integer block) {
        userDao.block(userId,block);
    }
}
